<script lang="ts" setup>
import { showConfirmDialog, showFailToast, showToast } from 'vant'
import { baseUrl } from '~/api'
import { OrderApi } from '~/api/OrderApi'
import LxButton from '~/components/common/LxButton.vue'
import { OrderModel } from '~/model'
import { Common } from '~/common'
import { protectedAction } from '~/utils'
import Compressor from 'compressorjs'

const route = useRoute()
const router = useRouter()
const fileInput = ref(null as null | HTMLInputElement)

const id = Number.parseInt(route.query.id as string)
const order = ref(null as OrderModel | null)

onMounted(async () => {
  order.value = await OrderApi.get(id)

  if (fileInput.value) {
    // fileInput.value.addEventListener('change', fileUpload)
  }
})

function onRecordStub() {
  fileInput.value!.click()
}

async function fileUpload() {
  console.log(1)

  if (!order.value) {
    return
  }
  const img = fileInput.value!.files![0]

  new Compressor(img, {
    quality: 0.3,

    // The compression process is asynchronous,
    // which means you have to access the `result` in the `success` hook function.
    success(result) {
      // console.log('----------------------');
      // console.log(img);
      // console.log('----------------------');
      // console.log(result);
      // console.log('----------------------');
      
      OrderApi.uploadStub(order.value!.id, new File([result], img.name))
        .then(ok => {
          if (ok) {
            // showSuccessToast('上传成功')
            showConfirmDialog({
              message: '上传成功，是否返回主页',
              confirmButtonText: '返回主页',
              cancelButtonText: '取消',
            })
            .then(() => {
              router.push('/')
            })
            .catch(() => {
              setTimeout(() => {
                location.reload()
              }, 500)
            })
          } else {
            showFailToast('上传失败，请联系管理员')
          }
        })
    },
    error(err) {
      showFailToast(err.message);
    },
  })

  
}

function onShare() {
  showToast('长按图片进行分享')
}

function onChange() {
  // dialogChange.value!.show()
  protectedAction(onRecordStub, '你确定要替换存根吗？原来的照片不会被保留')
}

function getUrl(order: OrderModel) {
  return `${baseUrl}${order.stub}`
}
</script>

<template>
  <div v-if="order" h-full w-full px4 py2>
    <PairsView
      mt2 :pairs="[
        ['客户', order.consumer!.name],
        ['批次', `第 ${order.batch} 单`],
        ['时间', Common.timeFormat(order.date)],
      ]"
    />
    <div v-if="order.stub">
      <div h="80%" w-full>
        <img h-full w-full :src="getUrl(order)" alt="">
      </div>
      <div my mt2 w-full flex text-size-4 c-white>
        <LxButton icon="brush" title="替换" color="orange" :action="onChange" />
        <LxButton icon="share-nodes" title="分享" color="mediumseagreen" :action="onShare" />
      </div>
    </div>

    <div v-else b="1px dashed gray" h-60vh w-full flex items-center justify-center text-center @click="onRecordStub">
      <div>存根尚未录入<br>点此录入</div>
    </div>
    <input
      id="stub"
      ref="fileInput"
      type="file"
      name="avatar"
      accept="image/*"
      hidden
      @change="fileUpload"
    >
  </div>
</template>

<style scoped>

</style>

<route lang="yaml">
meta:
  title: 存根
</route>
